import React, { useState, useEffect, useRef } from 'react';
import { useNavigate, useLocation } from 'react-router-dom';
import { FloatButton, Badge, message } from 'antd';
import {
  MenuOutlined,
  DashboardOutlined,
  ClockCircleOutlined,
  BookOutlined,
  TeamOutlined,
  MessageOutlined,
  RobotOutlined,
  CloudOutlined,
  NodeIndexOutlined,
  AimOutlined,
  BellOutlined,
  UserOutlined,
  SettingOutlined,
  LogoutOutlined,
  ExperimentOutlined,
} from '@ant-design/icons';
import { useAuth } from '../store/AuthContext';
import { notificationService } from '../services/api';
import './FloatingNavigation.css';

const FloatingNavigation: React.FC = () => {
  const navigate = useNavigate();
  const location = useLocation();
  const { logout } = useAuth();
  
  // 控制菜单显示/隐藏状态
  const [isVisible, setIsVisible] = useState(true);
  const [isHovered, setIsHovered] = useState(false);
  const isHoveredRef = useRef(false);
  const hideTimerRef = useRef<NodeJS.Timeout | null>(null);
  

  // 创建测试通知
  const createTestNotification = async () => {
    try {
      const response = await notificationService.createTestNotification();
      if (response.success) {
        message.success('测试通知创建成功！');
      } else {
        message.error('创建测试通知失败');
      }
    } catch (error) {
      console.error('创建测试通知失败:', error);
      message.error('创建测试通知失败');
    }
  };

  // 处理菜单项点击
  const handleMenuClick = (key: string) => {
    switch (key) {
      case 'notifications':
        navigate('/notification');
        break;
      case 'profile':
        navigate('/profile');
        break;
      case 'settings':
        navigate('/settings');
        break;
      case 'logout':
        logout();
        break;
      case 'test-notification':
        createTestNotification();
        break;
      default:
        navigate(key);
        break;
    }
  };

  // 监听鼠标位置，控制菜单显示/隐藏
  useEffect(() => {
    let hideTimer: NodeJS.Timeout;

    const handleMouseMove = (e: MouseEvent) => {
      const { clientX, clientY } = e;
      
      // 定义左上角触发区域（100px x 100px）
      const triggerArea = {
        x: 0,
        y: 0,
        width: 100,
        height: 100
      };

      // 检查鼠标是否在触发区域内
      const isInTriggerArea = 
        clientX >= triggerArea.x && 
        clientX <= triggerArea.x + triggerArea.width &&
        clientY >= triggerArea.y && 
        clientY <= triggerArea.y + triggerArea.height;

      if (isInTriggerArea) {
        // 鼠标在触发区域内，显示菜单但不展开
        clearTimeout(hideTimer);
        setIsVisible(true);
        // 不在这里设置isExpanded，让handleMouseEnter处理
      } else if (!isHovered) {
        // 鼠标不在触发区域内且不在菜单上，延迟隐藏
        clearTimeout(hideTimer);
        hideTimer = setTimeout(() => {
          setIsVisible(false);
        }, 1000); // 1秒后隐藏
      }
    };

    // 添加鼠标移动监听
    document.addEventListener('mousemove', handleMouseMove);

    return () => {
      document.removeEventListener('mousemove', handleMouseMove);
      clearTimeout(hideTimer);
    };
  }, [isHovered]);

  // 组件卸载时清理计时器
  useEffect(() => {
    return () => {
      if (hideTimerRef.current) {
        clearTimeout(hideTimerRef.current);
      }
    };
  }, []);

  // 处理菜单悬停
  const handleMouseEnter = () => {
    // 清除之前的隐藏计时器
    if (hideTimerRef.current) {
      clearTimeout(hideTimerRef.current);
      hideTimerRef.current = null;
    }
    
    setIsHovered(true);
    isHoveredRef.current = true;
    setIsVisible(true);
  };

  const handleMouseLeave = () => {
    setIsHovered(false);
    isHoveredRef.current = false;
    
    // 清除之前的计时器
    if (hideTimerRef.current) {
      clearTimeout(hideTimerRef.current);
    }
    
    // 延迟隐藏，给用户时间重新进入触发区域
    hideTimerRef.current = setTimeout(() => {
      if (!isHoveredRef.current) {
        setIsVisible(false);
      }
      hideTimerRef.current = null;
    }, 1000); // 增加延迟时间到1秒
  };



  return (
    <div className="floating-navigation">
      <FloatButton.Group
        trigger="hover"
        type="primary"
        className={isVisible ? 'visible' : 'hidden'}
        style={{ 
          left: 24, 
          top: 24
        }}
        icon={<MenuOutlined />}
        shape="circle"
        onMouseEnter={handleMouseEnter}
        onMouseLeave={handleMouseLeave}
      >
      {/* 用户功能菜单项 - 反转后显示在顶部 */}
      <FloatButton
        icon={<LogoutOutlined />}
        tooltip={{ title: "退出登录", placement: "left" }}
        onClick={() => handleMenuClick('logout')}
        onMouseEnter={handleMouseEnter}
        onMouseLeave={handleMouseLeave}
      />
      <FloatButton
        icon={<SettingOutlined />}
        tooltip={{ title: "设置", placement: "left" }}
        onClick={() => handleMenuClick('settings')}
        onMouseEnter={handleMouseEnter}
        onMouseLeave={handleMouseLeave}
      />
      <FloatButton
        icon={<UserOutlined />}
        tooltip={{ title: "个人信息", placement: "left" }}
        onClick={() => handleMenuClick('profile')}
        onMouseEnter={handleMouseEnter}
        onMouseLeave={handleMouseLeave}
      />
      <FloatButton
        icon={<ExperimentOutlined />}
        tooltip={{ title: "测试通知", placement: "left" }}
        onClick={() => handleMenuClick('test-notification')}
        onMouseEnter={handleMouseEnter}
        onMouseLeave={handleMouseLeave}
      />
      <FloatButton
        icon={<BellOutlined />}
        tooltip={{ title: "通知", placement: "left" }}
        onClick={() => handleMenuClick('notifications')}
        onMouseEnter={handleMouseEnter}
        onMouseLeave={handleMouseLeave}
      />
      
      {/* 页面导航菜单项 - 反转后显示在底部 */}
      <FloatButton
        icon={<NodeIndexOutlined />}
        tooltip={{ title: "知识图谱", placement: "left" }}
        onClick={() => handleMenuClick('/knowledge-graph')}
        className={location.pathname === '/knowledge-graph' ? 'active' : ''}
        onMouseEnter={handleMouseEnter}
        onMouseLeave={handleMouseLeave}
      />
      <FloatButton
        icon={<AimOutlined />}
        tooltip={{ title: "职业规划", placement: "left" }}
        onClick={() => handleMenuClick('/career-plan')}
        className={location.pathname === '/career-plan' ? 'active' : ''}
        onMouseEnter={handleMouseEnter}
        onMouseLeave={handleMouseLeave}
      />
      <FloatButton
        icon={<CloudOutlined />}
        tooltip={{ title: "网盘", placement: "left" }}
        onClick={() => handleMenuClick('/cloud-storage')}
        className={location.pathname === '/cloud-storage' ? 'active' : ''}
        onMouseEnter={handleMouseEnter}
        onMouseLeave={handleMouseLeave}
      />
      <FloatButton
        icon={<RobotOutlined />}
        tooltip={{ title: "AI交流", placement: "left" }}
        onClick={() => handleMenuClick('/ai-chat')}
        className={location.pathname === '/ai-chat' ? 'active' : ''}
        onMouseEnter={handleMouseEnter}
        onMouseLeave={handleMouseLeave}
      />
      <FloatButton
        icon={<MessageOutlined />}
        tooltip={{ title: "聊天", placement: "left" }}
        onClick={() => handleMenuClick('/chat')}
        className={location.pathname === '/chat' ? 'active' : ''}
        onMouseEnter={handleMouseEnter}
        onMouseLeave={handleMouseLeave}
      />
      <FloatButton
        icon={<TeamOutlined />}
        tooltip={{ title: "好友", placement: "left" }}
        onClick={() => handleMenuClick('/friends')}
        className={location.pathname === '/friends' ? 'active' : ''}
        onMouseEnter={handleMouseEnter}
        onMouseLeave={handleMouseLeave}
      />
      <FloatButton
        icon={<BookOutlined />}
        tooltip={{ title: "学习规划", placement: "left" }}
        onClick={() => handleMenuClick('/study-plan')}
        className={location.pathname === '/study-plan' ? 'active' : ''}
        onMouseEnter={handleMouseEnter}
        onMouseLeave={handleMouseLeave}
      />
      <FloatButton
        icon={<ClockCircleOutlined />}
        tooltip={{ title: "专注模式", placement: "left" }}
        onClick={() => handleMenuClick('/focus')}
        className={location.pathname === '/focus' ? 'active' : ''}
        onMouseEnter={handleMouseEnter}
        onMouseLeave={handleMouseLeave}
      />
      <FloatButton
        icon={<DashboardOutlined />}
        tooltip={{ title: "首页", placement: "left" }}
        onClick={() => handleMenuClick('/dashboard')}
        className={location.pathname === '/dashboard' ? 'active' : ''}
        onMouseEnter={handleMouseEnter}
        onMouseLeave={handleMouseLeave}
      />
      </FloatButton.Group>
    </div>
  );
};

export default FloatingNavigation;
